package com.ruoyi.websocket.utils;

import org.springframework.web.socket.WebSocketSession;

import java.util.*;
import java.util.concurrent.ConcurrentHashMap;

public class WebSocketUserSessionUtil {
    private static final Map<String, WebSocketSession> sessions = new ConcurrentHashMap<>();

    public static void addSession(String userId, WebSocketSession session) {
        sessions.put(userId, session);
    }

    public static void removeSession(WebSocketSession session) {
        String userId = (String) session.getAttributes().get("userId");
        sessions.remove(userId);
    }

    public static Collection<WebSocketSession> getAllSessions() {
        return sessions.values();
    }

    public static WebSocketSession getSession(String userId) {
        return sessions.get(userId);
    }

    public static int getOnlineCount() {
        return sessions.size();
    }

    public static List<Map<String, String>> getOnlineUserList() {
        List<Map<String, String>> list = new ArrayList<>();
        for (WebSocketSession session : sessions.values()) {
            Map<String, String> user = new HashMap<>();
            user.put("userId", (String) session.getAttributes().get("userId"));
            user.put("nickname", (String) session.getAttributes().get("nickname"));
            list.add(user);
        }
        return list;
    }
}

